package edu.cs.networkmonitor.scheduler;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import edu.cs.networkmonitor.application.MonitorBoard;
import edu.cs.networkmonitor.devices.BaseSource;
import edu.cs.networkmonitor.utils.EmailUtil;

public class NetTaskScheduler {

	private List<BaseSource> _sources;
	private Map<BaseSource, ScheduledExecutorService> _taskMap;

	public NetTaskScheduler() {
		_sources = new ArrayList<BaseSource>();
		_taskMap = new HashMap<BaseSource, ScheduledExecutorService>();
	}

	public boolean addSource(BaseSource s) {
		if(!_sources.contains(s)){
			_sources.add(s);
			return true;
		}
		return false;
	}

	public void scheduleTask(final BaseSource s, final MonitorBoard monitorInterface) {
		System.out.println("Scheduling " + s.getSourceName());
		if(_taskMap.get(s) != null){
			System.out.println(s.getSourceName() + " already scheduled.");
			return;
		}
		ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
		
		Runnable periodicTask = new Runnable() {
			public void run() {
				// Invoke method(s) to do the work
				if(!s.connect()){
					System.out.println("Failed to connect " + s.getSourceName());
					EmailUtil.sendEmail(s.getEmailList(), s.getEmailSubject(), s.getEmailBody());
				} else {
					System.out.println("Connected to " + s.getSourceName() + new Date().toString());
					//EmailUtil.sendEmail(s.getEmailList(), s.getEmailSubject(), s.getEmailBody());
				}
				monitorInterface.repaintMonitor();
			}
		};
       executor.scheduleAtFixedRate(periodicTask, 0, s.getTime(), TimeUnit.MINUTES);
		_taskMap.put(s, executor);
	}

	public void stopScheduledTask(BaseSource s) {
		System.out.println("Stoping " + s.getSourceName());
		if(_sources.contains(s)) {
			ScheduledExecutorService service = _taskMap.get(s);
			if(service != null) {
				service.shutdown();
				_taskMap.remove(s);
			}
		}
	}
	public void removeScheduledTask(BaseSource s) {
		System.out.println("Removing " + s.getSourceName());
		_sources.remove(s);
		ScheduledExecutorService service = _taskMap.get(s);
		if(service != null) {
			service.shutdown();
			_taskMap.remove(s);
		}
	}
	
	public List<BaseSource> getSources() {
		return _sources;
	}
	
	public boolean isSourceRunning(BaseSource s) {
		return (_taskMap.get(s) != null); 
	}
}
